import axios from 'axios';
import React, {useContext, useEffect, useState} from 'react';
import {Link, useNavigate} from 'react-router-dom';
import Spinner from '../components/Spinner';
import {UserContext} from "../context/userContext";
import {AutoCenter, Avatar, Empty, NavBar, Popover, Space} from "antd-mobile";
import dayjs from "dayjs";

const Message = () => {
  const [msg, setMsg] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [avatar, setAvatar] = useState('');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [createdAt, setCreatedAt] = useState(null);
  const navigate = useNavigate();
  const { currentUser } = useContext(UserContext);
  const token = currentUser?.token;

  const back = () => {
    navigate(-1);
  }
  useEffect(() => {
    if (!token) {
      navigate('/login');
    }
  }, [token, navigate]);

  useEffect(() => {
    const getUser = async () => {
      if (!currentUser?.id) {
        console.log('no user id')
        return;
      }
      try {
        const response = await axios.get(
            `${process.env.REACT_APP_BASE_URL}/users/${currentUser.id}`,
            { withCredentials: true, headers: { Authorization: `Bearer ${token}` } }
        );

        const { name, email, avatar, createdAt, messages } = response.data;
        setName(name);
        setEmail(email);
        setAvatar(avatar);
        setCreatedAt(createdAt);
        setMsg(messages);
      } catch (error) {
        console.log(error);
      }
    };

    getUser();
  }, [currentUser?.id, token]);


  if (isLoading) {
    return <Spinner />
  }

  return (
    <section className='posts'>
      <NavBar style={{'background-color': 'rgba(80, 62, 157, 1)', 'color': 'white'}} onBack={back}>我的消息</NavBar>

      {msg.length > 0 ? <div className="container authors__container">

        {msg.map(({_id: id, text: message, created}) => {
          return <Space direction='vertical' align='baseline' wrap>
            <p>{dayjs(created).format('YYYY-MM-DD HH:mm:ss')}</p>
            <Popover
                content={message}
                placement='right-end'
                defaultVisible>
              <Avatar src={`${process.env.REACT_APP_ASSETS_URL}/uploads/${avatar}`} alt=""/>
            </Popover>
          </Space>
        })}
      </div> : <AutoCenter><Empty/></AutoCenter>}
    </section>
  )
}

export default Message
